package com.zx.mes.hyl.spring;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * redis spring support <br>
 * 官网地址:https://lettuce.io/core/release/reference/index.html#spring.spring-data-redis <br>
 *
 * @author 华云龙
 * @date 2018-12-27
 */
@Configuration
public class RedisSpringSupport {

    private final RedisProperties redisProperties;

    public RedisSpringSupport(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    @Bean(destroyMethod = "shutdown")
    public ClientResources clientResources() {
        return DefaultClientResources.create();
    }

    @Bean(destroyMethod = "shutdown")
    public RedisClient redisClient(ClientResources clientResources) {
        RedisClient redisClient = RedisClient.create(clientResources, RedisURI.create(redisProperties.getUrl(), redisProperties.getPort()));
        redisClient.setDefaultTimeout(Duration.ofMinutes(1));
        return redisClient;
    }

    @Bean(destroyMethod = "close")
    public StatefulRedisConnection<String, String> connection(RedisClient redisClient) {
        return redisClient.connect();
    }
}
